/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#ifndef MK_HTTP_SESSION_H
#define MK_HTTP_SESSION_H
#include "MkTcp/MkTcpSession.h"
#include "MkHttpRequest.h"
#include "MkWebSocketMessage.h"
#include "MkHttpUtil.h"
#include "MkEvent/MkTimer.h"

class CMkHttpServer;
class MkApi CMkHttpSession :public CMkTcpSession
{
public:
    CMkHttpSession(CMkEvent *pEvent, CMkTimer* pTimer, CMkHttpServer* parent);
    virtual ~CMkHttpSession();

    Uint32 SendReply(const MkHttpStatusCode& Error, const MkHttpBodyType& BodyType = MkHttpBodyTypeNone, const MkString& Body = "");
    Uint32 SendFileReply(FILE* pFile, Uint64 FileSize);

    Uint32 SendWebsocketConnectResponse(const CMkHttpRequest& Request);
    Uint32 SendWebSocketText(const MkString& Content, BOOL bMark = FALSE);
    Uint32 SendWebSocketBinary(const CMkBufferList& BufList, BOOL bMark = FALSE);
    Uint32 WebsocketSendClose();
    const BOOL IsWebSocket() const { return m_bWebSocket; }
    void SetSendPingFlag(BOOL bSendPing) { m_bSendPing = bSendPing; }
protected:
private:
    Uint32 OnRecv() override;
    Uint32 OnWrite() override;
    Uint32 Check(const CMkTime& NowTime) override;
private:
    Uint32 WebSocketRecvParse(const Uint8* pBuf, Uint32 nLen, Uint32& nUsed);
    Uint32 HttpRecvParse(const Uint8* pBuf, Uint32 nLen, Uint32& nUsed);
    Uint32 SendWebSocketReply(const MkString& WsAccept, const MkString& Protocol);
    Uint32 WebSocketSendPing();
    Uint32 WebSocketSendPong();
private:
    BOOL                    m_bWebSocket;
    BOOL                    m_bSendPing;
    CMkHttpServer           *m_pParent;
    Uint32                  m_CurHttpRequests;
    FILE*                   m_pReplyFp;

    Uint8                   *m_pRecvBuffer;
    Uint32                  m_nOffset;
    Uint32                  m_nLen;

    CMkHttpRequest    m_Request;
    CMkWebSocketMessage     m_WebSocketMsg1;
    MkString                m_WebSocketMsg;
};

#endif